﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Server;


[Serializable]
[SqlUserDefinedAggregate(Format.Native)]
public struct ProbComb
{
    private SqlDouble _Mul;
    private SqlDouble _NegMul;

    public void Init()
    {
        _Mul = 1;
        _NegMul = 1;
    }

    public void Accumulate(SqlDouble Value)
    {
        if (Value > 0.05 && Value < 0.95)
        {
            _Mul *= Value.Value;
            _NegMul *= (1.0 - Value.Value);
        }
    }

    public void Merge(ProbComb Group)
    {
        _Mul *= Group._Mul;
        _NegMul *= Group._NegMul;
    }

    public SqlDouble Terminate()
    {
        var div = (_Mul + _NegMul);
        if(div == 0)
            return 0;
        var result = _Mul / div;
        return result;
    }
}
